(def collider-info "A package for producing ANSI escape sequences.")
(use ./common)
(def [ansi-pfx ansi-sep ansi-sfx ansi-6-fg ansi-6-bg ansi-8-fg ansi-8-bg]
     ["\e["    ";"      "m"      "38;5"    "48;5"    "38;2"    "48;2"   ])
(defn RGB256 ( &opt red green blue ground)
  (default red 0)
  (default green 0)
  (default blue 0)
  (def [red green blue] (map math/round [red green blue]))
  (default ground :fg)
  (string ansi-pfx
          (if (= :bg ground) ansi-8-bg ansi-8-fg) ansi-sep
          red ansi-sep
          green ansi-sep
          blue ansi-sfx))


(defn RGB1 (&opt red green blue ground)
  (default red 0)
  (default green 0)
  (default blue 0)
  (def [red green blue] (map math/round (map (. * 256) [red green blue])))
  (default ground :fg)
  (RGB256 red green blue ground)
  )
(defn RGB6 ( &opt red green blue ground) # n,n,n,w
   (default red 0)
  (default green 0)
  (default blue 0)
  (default ground :fg)
  (string ansi-pfx
            (if (= :bg ground) ansi-6-bg ansi-6-fg) ansi-sep
            (if (= red green blue)
              (+ 232 (* red 4))
              (+ 16 blue (* 6 green) (* 36 red) ))
          ansi-sfx))
(def COL16s { :black 30 :000 30 :0 30
             :red 31 :green 32 :yellow 33 :blue 34
             :purple 35 :magenta 35
             :cyan 36 :white 37
             :bright-black 90 :grey 90 :gray 90
             :bright-red 91 :light-red 91
             :bright-green 92 :light-green 92
             :bright-yellow 93 :light-yellow 93
             :bright-blue 94 :light-blue 94
             :bright-purple 95 :light-purple 95 :bright-magenta 95 :light-magenta 95
             :bright-cyan 96 :light-cyan 96
             :bright-white 97 :light-white 97 :fff 97 :4095 97}) # 0xfff is white
(defn COL16 ( &opt disc ground) # n|w,w
  (if-let (
           col-raw (get COL16s (keyword disc))
           col-value (+
                      (if (< 37 col-raw) 60 0)
                      (if (= :bg ground) 10 0)
                      col-raw))
    (string ansi-pfx col-value ansi-sfx)))
(defn display-2d-matrix (matrix)
   (print ;(flatten
            (interpose "\n"
                       (map (. map |(string (RGB1 (math/sqrt $) (* $ $) 0 :bg) " "))
                            matrix)))))
